﻿
using System.Text.Json.Nodes;
using Android.Gms.Extensions;
using Android.Gms.Tasks;
using Android.Graphics;
using Android.Views.InputMethods;
using Xamarin.Google.MLKit.Vision.Common;
using Xamarin.Google.MLKit.Vision.Text;
using Xamarin.Google.MLKit.Vision.Text.Chinese;

namespace ScreenShotDemo
{
    /// <summary>
    /// mlkit图文识别实现类
    /// </summary>
    public class MlKitHelper
    {
        private ChineseTextRecognizerOptions? _options;
        private ITextRecognizer? _textRecognizer;
        private static MlKitHelper? _instance;
        public MlKitHelper()
        {
            _options = new ChineseTextRecognizerOptions.Builder().Build();
            _textRecognizer = TextRecognition.GetClient(_options);
        }
        public static MlKitHelper? GetMlKitHelper()
        {
            if (_instance == null)
            {
                _instance = new MlKitHelper();
            }
            return _instance;
        }
        /// <summary>
        /// 图像文本识别
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        public async Task<JsonObject?> GetTextFlags(Bitmap bitmap) 
        {
            try
            {
                InputImage inputImage = InputImage.FromBitmap(bitmap, 0);
                JsonObject ret = new JsonObject();
                var result = await _textRecognizer.Process(inputImage)
                    .AddOnSuccessListener(new OnSuccessListener(result =>
                    {
                        ret.Add("text", result.GetText());
                        ret.Add("flag", 0);
                    }))
                    .AddOnFailureListener(new OnFailureListener(result =>
                    {
                        ret.Add("text", result.Message);
                        ret.Add("flag", -1);
                    }));
                inputImage.Dispose();
                return ret;
            }
            catch (Exception e)
            {
                CommUtils.WriteLog($"获取文本失败{e.Message}");
                return null;
            }
            finally 
            {
                bitmap.Dispose();
            }
            
        }
        /// <summary>
        /// 识别指定区域的文本
        /// </summary>
        /// <param name="bitmap"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        public async Task<JsonObject?> GetTextFlags(Bitmap bitmap,int x,int y,int width,int height)
        {
            try 
            {
                JsonObject ret = new JsonObject();
                Bitmap resultBitmap = Bitmap.CreateBitmap(bitmap, x, y, width, height);
                InputImage inputImage = InputImage.FromBitmap(resultBitmap, 0);
                var result = await _textRecognizer.Process(inputImage)
                    .AddOnSuccessListener(new OnSuccessListener(result =>
                    {
                        ret.Add("text", result.GetText());
                        ret.Add("flag", 0);
                    }))
                    .AddOnFailureListener(new OnFailureListener(result =>
                    {
                        ret.Add("text", result.Message);
                        ret.Add("flag", -1);
                    }));
                resultBitmap.Dispose();
                inputImage.Dispose();
                return ret;
            }
            catch (Exception e)
            {
                CommUtils.WriteLog($"获取文本失败{e.Message}");
                return null;
            }
            finally
            {
                bitmap.Dispose();
            }
        }

        public void Dispose()
        {
            _textRecognizer?.Close();
        }

        /// <summary>
        /// 处理成功的回调
        /// </summary>
        private class OnSuccessListener : Java.Lang.Object, IOnSuccessListener
        {
            private readonly Action<Text> _onSuccess;

            public OnSuccessListener(Action<Text> onSuccess)
            {
                _onSuccess = onSuccess;
            }
            public void OnSuccess(Java.Lang.Object result)
            {
                if (result is Text textResult)
                {
                    _onSuccess(textResult);
                }
            }
        }
        /// <summary>
        /// 处理失败的回调
        /// </summary>
        private class OnFailureListener : Java.Lang.Object, IOnFailureListener
        {
            private readonly Action<Exception> _onFailure;
            public OnFailureListener(Action<Exception> onFailure)
            {
                _onFailure = onFailure;
            }
            public void OnFailure(Java.Lang.Exception e)
            {
                _onFailure(new Exception(e.Message));
            }
        }
        
    }
}
